<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>轮播图</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        .carousel-container {
            width: 800px;
            height: 400px;
            margin: 50px auto;
            position: relative;
            overflow: hidden;
        }

        .active {
            display: block;
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .hidden{
            display: none;
        }

        .nav {
            position: absolute;
            top: 50%;
            width: 100%;
            display: flex;
            justify-content: space-between;
        }

        .nav button {
            background-color: rgba(0, 0, 0, 0.5);
            color: white;
            border: none;
            padding: 10px;
            cursor: pointer;
        }


    </style>
</head>
<body>
<div class="carousel-container">
    <div class="carousel-track">
        <img src="./1.jpg" class="active">
        <img src="./2.jpg" class="hidden">
        <img src="./3.png" class="hidden">
        <img src="./4.jpg" class="hidden">
    </div>

    <!-- 左右按钮 -->
    <div class="nav">
        <button class="prev-btn">&#10094;</button>
        <button class="next-btn">&#10095;</button>
    </div>

    <!-- 指示器 -->
    <div class="indicators"></div>
</div>

<script>

    const prevBtn = document.querySelector('.prev-btn')
    const nextBtn = document.querySelector('.next-btn')
    let currentIndex = 0

    //播放某一个幻灯片的方法
    function play(index){
        //获取所有的图片
        const images = document.querySelectorAll('.carousel-track img')
        //获取指示器
        const indicators = document.querySelector('.indicators')

        //判断index是否超出范围
        if(index < 0){
            index = images.length - 1
        }else if(index >= images.length){
            index = 0
        }

        //遍历所有的图片，隐藏所有的图片
        images.forEach((image, i) => {
            if(i === index){
                currentIndex = index
                image.classList.add('active')
                image.classList.remove('hidden')
            }else{
                image.classList.remove('active')
                image.classList.add('hidden')
            }
        });
    }

    prevBtn.addEventListener('click', () => {
        play(currentIndex - 1)
    })

    nextBtn.addEventListener('click', () => {
        play(currentIndex + 1)
    });

    //初始化
    play(currentIndex)

    //自动播放
    setInterval(() => {
        play(currentIndex + 1)
    }, 1500)

</script>
</body>
</html>
